﻿Imports System.Data.SqlServerCe
Imports System.Reflection

Namespace SQLCompactDataAccess

    Public Class DataReaderReflectionBuilder(Of T)

        Private Shared _objDataReaderReflectionBuilders As New Dictionary(Of Type, DataReaderReflectionBuilder(Of T))
        Private _objProperties As PropertyInfo()
        Private Sub New()
        End Sub

        Public Function Build(ByVal objReader As SqlCeDataReader) As T

            Dim objReturnValue As T = DirectCast(Activator.CreateInstance(GetType(T)), T)

            For intX As Integer = 0 To objReader.FieldCount - 1

                If _objProperties(intX) IsNot Nothing AndAlso Not objReader.IsDBNull(intX) Then
                    _objProperties(intX).SetValue(objReturnValue, objReader(intX), Nothing)
                End If

            Next

            Return objReturnValue
        End Function

        Public Shared Function CreateBuilder(ByVal objReader As SqlCeDataReader) As DataReaderReflectionBuilder(Of T)

            Dim objBuilder As DataReaderReflectionBuilder(Of T) = Nothing

            If Not _objDataReaderReflectionBuilders.TryGetValue(GetType(T), objBuilder) Then
                objBuilder = New DataReaderReflectionBuilder(Of T)
            End If

            objBuilder._objProperties = New PropertyInfo(objReader.FieldCount - 1) {}

            For intX As Integer = 0 To objReader.FieldCount - 1
                objBuilder._objProperties(intX) = GetType(T).GetProperty(objReader.GetName(intX))
            Next

            Return objBuilder
        End Function

    End Class

End Namespace
